﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Estimate
{
    public partial class formBudgetCreate : FormMDIChildTemplate
    {
        private Object currentObject;
        public formBudgetCreate(Object currentObject)
        {
            this.currentObject = currentObject;
            InitializeComponent();
        }

        private void formBudgetCreate_Load(object sender, EventArgs e)
        {
            Text = String.Format("Формування Кошторису [{0}]", currentObject.ObjectShortName);
            root.TranslateGrid(gridProduct);
            root.TranslateGrid(gridWork);
            root.TranslateGrid(gridSelectedProduct);
            root.TranslateGrid(gridSelectedWork);

            workCategoryBindingSource.DataSource = context.WorkCategories.OrderBy(x => x.WorkCategoryName);
            objectWorkCategoryBindingSource.DataSource = currentObject.ObjectWorkCategories.ToList();
            unitBindingSource.DataSource = context.Units.OrderBy(x => x.UnitName);

            LoadProduct();
            LoadWork();
            LoadSelectedWork();
            LoadSelectedProduct();
        }

        private void LoadWork()
        {
            string code = textBoxWorkCode.Text;
            string name = textBoxWorkName.Text;
            var works = from x in context.Works select x;
            if (code != "") works = works.Where(x => x.WorkCode.Contains(code));
            if (name != "") works = works.Where(x => x.WorkName.Contains(name));
            workBindingSource.DataSource = works;
        }

        private void Work_textChanged(object sender, EventArgs e)
        { LoadWork(); }

        private void LoadProduct()
        {
            string code = textBoxProductCode.Text;
            string name = textBoxProductName.Text;
            var products = context.Products.Select(x => x);
            if (code != "") products = products.Where(x => x.ProductCode.Contains(code));
            if (name != "") products = products.Where(x => x.ProductName.Contains(name));
            productBindingSource.DataSource = products;
        }

        private void Product_textChanged(object sender, EventArgs e)
        { LoadProduct(); }


        private void LoadSelectedProduct()
        {

            var selectedProducts = from product in context.Products
                                   from budget in context.BudgetProducts
                                   where budget.Product == product && budget.Object == currentObject
                                   select new ProductInStoreHouse
                                              {
                                                  Count = budget.cnt,
                                                  ProductId = budget.BudgetProductID,
                                                  ProductName = product.ProductName,
                                                  Unit = product.Unit
                                              };
            productInStoreHouseBindingSource.DataSource = selectedProducts;
        }

        private void buttonProductAdd_Click(object sender, EventArgs e)
        {
            Product currentProduct = (Product)productBindingSource.Current;
            if (currentProduct == null) return;
            decimal count = 0;
            try
            {
                count = decimal.Parse(textBoxProductCount.Text);
            }
            catch
            {
                return;
            }
            BudgetProduct budgetProduct = new BudgetProduct();
            budgetProduct.cnt = count;
            budgetProduct.Product = currentProduct;
            context.BudgetProducts.InsertOnSubmit(budgetProduct);
            currentObject.BudgetProducts.Add(budgetProduct);
            root.Submit(false);
            LoadSelectedProduct();

        }

        private void buttonProductRemove_Click(object sender, EventArgs e)
        {
            ProductInStoreHouse product =
                (ProductInStoreHouse)productInStoreHouseBindingSource.Current;
            if (product != null)
            {
                context.BudgetProducts.DeleteAllOnSubmit(
                    context.BudgetProducts.Where(x => x.BudgetProductID == product.ProductId));
                root.Submit();
                LoadSelectedProduct();
            }
        }

        private void LoadSelectedWork()
        {
            if (objectWorkCategoryBindingSource.Current != null)
            {
                var selectedWorks = from work in context.Works
                                    from budget in context.BudgetWorks
                                    where
                                        budget.Work == work &&
                                        budget.ObjectWorkCategory == objectWorkCategoryBindingSource.Current
                                    select new ProductInStoreHouse()
                                               {
                                                   Count = budget.cnt,
                                                   ProductId = budget.BudgetWorkID,
                                                   ProductName = work.WorkName,
                                                   Unit = work.Unit
                                               };
                productInStoreHouseBindingSource1.DataSource = selectedWorks;
            }
        }

        private void buttonWorkAdd_Click(object sender, EventArgs e)
        {
            Work currentWork = null;
            if (checkBoxNewWork.Checked)
            {
                Work work = new Work();
                work.Price = decimal.Parse(textBoxWorkPrice.Text);
                work.Unit = (Unit)unitBindingSource.Current;
                work.WorkCategory = (WorkCategory)workCategoryBindingSource.Current;
                work.WorkCode = textBoxNewWorkCode.Text;
                work.WorkName = textBoxNewWorkName.Text;
                context.Works.InsertOnSubmit(work);
                root.Submit();
                currentWork = work;
            }
            else currentWork = (Work)workBindingSource.Current;
            if (currentWork == null) return;
            decimal count = 0;
            try
            {
                count = decimal.Parse(textBoxWorkCount.Text);
            }
            catch
            {
                return;
            }
            BudgetWork budgetWork = new BudgetWork();
            budgetWork.cnt = count;
            budgetWork.ObjectWorkCategory = (ObjectWorkCategory)objectWorkCategoryBindingSource.Current;
            budgetWork.Work = currentWork;
            context.BudgetWorks.InsertOnSubmit(budgetWork);
            root.Submit();
            LoadSelectedWork();
        }

        private void buttonWorkRemove_Click(object sender, EventArgs e)
        {
            ProductInStoreHouse work =
                (ProductInStoreHouse)productInStoreHouseBindingSource1.Current;
            if (work != null)
            {
                context.BudgetWorks.DeleteAllOnSubmit(
                context.BudgetWorks.Where(x => x.BudgetWorkID == work.ProductId));
                root.Submit();
                LoadSelectedWork();
            }
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            Budget budget = new Budget(context, currentObject);
            budget.ShowBudget();
            #region trash
            /*
            if (currentObject != null)
            {
                Budget budget = new Budget(context, currentObject);
                reportBudget  reportBudget = new reportBudget();

                reportBudget.xrLabelAdd1.Visible = false;
                reportBudget.xrLabelAdd2.Visible = false;
                reportBudget.xrLabelAdd3.Visible = false;

                reportBudget.bindingSourceProduct.DataSource  = budget.Products;
                reportBudget.bindingSourceWork .DataSource = budget.Works;

                reportBudget.xrLabelFirm1.Lines = currentObject.Firm.GetFullDescription();
                reportBudget.xrLabelFirm2.Lines = db.GetFirmOwn().GetFullDescription();
                reportBudget.xrLabelObject.Text = currentObject.ObjectName;

                reportBudget.xrLabelPart1.Text = budget.Part1.ToString();
                reportBudget.xrLabelPart1Total.Text = budget.Part1Total.ToString();
                reportBudget.xrLabelTaxCurrent.Text = budget.TaxCurrent.ToString();
                reportBudget.xrLabelTaxCurrentP.Text = currentObject.TaxCurrent.ToString();

                reportBudget.xrLabelPart2.Text = budget.Part2.ToString();
                reportBudget.xrLabelTaxStorehouse.Text  = budget.TaxStorehouse.ToString();
                reportBudget.xrLabelTaxStorehouseP.Text = currentObject.TaxStorehouse.ToString();
                reportBudget.xrLabelTaxTransport.Text = budget.TaxTransport.ToString();
                reportBudget.xrLabelTaxTransportP.Text = currentObject.TaxTransport.ToString();
                reportBudget.xrLabelPart2Total.Text = budget.Part2Total.ToString();
                reportBudget.xrLabelPart12.Text = budget.Part12.ToString();

                reportBudget.xrLabelTaxAdmin.Text = budget.TaxAdmin.ToString();
                reportBudget.xrLabelTaxAdminP.Text = currentObject.TaxAdmin.ToString();
                reportBudget.xrLabelTaxProfit.Text = budget.TaxProfit.ToString();
                reportBudget.xrLabelTaxProfitP.Text = currentObject.TaxProfit.ToString();
                reportBudget.xrLabelPart12Total.Text = budget.Part12Total.ToString();

                reportBudget.xrLabelTaxSingle.Text = budget.TaxSingle.ToString();
                //reportBudget.xrLabelTaxSingleP.Text = currentObject.TaxSingle.ToString();
                reportBudget.xrLabelTotal.Text = budget.Total.ToString();
                reportBudget.xrLabelTaxVat.Text = budget.TaxVat.ToString();
                reportBudget.xrLabelTaxVatP.Text = currentObject.TaxVat.ToString();
                reportBudget.xrLabelTotalTotal.Text = budget.TotalTotal.ToString();

                reportBudget.ShowPreview();

            }
             * */
            #endregion
        }

        private void comboBoxUnit_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void checkBoxNewWork_CheckedChanged(object sender, EventArgs e)
        {
            panelNewWork.Enabled = checkBoxNewWork.Checked;
        }

        private void objectWorkCategoryBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            LoadSelectedWork();
        }

        private void buttonProductNeed_Click(object sender, EventArgs e)
        {
            reportProductNeed reportProductNeed = new reportProductNeed();
            reportProductNeed.xrLabelDateset.Text = DateTime.Now.ToShortDateString();
            reportProductNeed.xrLabelFirm.Lines = db.GetFirmOwn().GetFullDescription() ;
            reportProductNeed.xrLabelObjectAddress.Text = currentObject.ObjectAddress;
            reportProductNeed.xrLabelObjectName.Text = currentObject.ObjectName;


            List<ProductInStoreHouse> products = new List<ProductInStoreHouse>();

            
            foreach (BudgetProduct budgetProduct in currentObject.BudgetProducts)
            {
                ProductInStoreHouse product = new ProductInStoreHouse();
                product.ProductName = budgetProduct.Product.ProductName;
                product.Unit = budgetProduct.Product.Unit;



                var cntIn =
                    budgetProduct.Product.ProductHistories.Where(
                        x =>
                        x.StatusID == 20).Sum(
                        x => x.Cnt);
                var cntOut = budgetProduct.Product.ProductHistories.Where(
                    x =>
                    x.StatusID == 30).Sum(
                    x => x.Cnt);

                var cnt = budgetProduct.cnt - cntIn - cntOut;
                
                if (cnt > 0)
                {
                    product.Count = cnt;
                    products.Add(product);


                }
            }
            reportProductNeed.DataSource = products;
            reportProductNeed.ShowPreview();
        }
    }
}

